/*
 * Copyright (c) 2015-2016 Beijing HuntingX Technology Co.,Ltd. All Rights Reserved.
 */
package com.hunting4x.p4x;

import com.hunting4x.error.RestResponseParseException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpRequests {

    private static final String WEBSITE_CN = "http://app.hunting4x.com.cn:9005/v1/";
    private static final int TIMEOUT = 30000;

    private String serviceSite = WEBSITE_CN;
    private String appId;
    private String appKey;

    private int httpTimeOut = TIMEOUT;

    public HttpRequests() {
        super();
    }
    
    public HttpRequests(String serviceSite) {
        this.serviceSite = serviceSite;
    }
    
    public HttpRequests(String serviceSite, String appId, String appKey) {
        this.serviceSite = serviceSite;
        this.appId = appId;
        this.appKey = appKey;
    }
    
    /**
     * 调用远程RESTful Service
     * 
     * @param service 资源大分类
     * @param action 具体资源
     * @param params POST参数
     * @return 调用结果
     * @throws RestResponseParseException
     */
    public JSONObject request(String service, String action, PostParameters params) throws RestResponseParseException {

        params.getMultiPart().addPart("appId", new StringBody(this.appId, ContentType.create("text/plain", "UTF-8")));
        params.getMultiPart().addPart("appKey", new StringBody(this.appKey, ContentType.create("text/plain", "UTF-8")));

        return request2(service, action, params);
    }
    
    /**
     * 调用远程RESTful Service
     * 
     * @param service 资源大分类
     * @param action 具体资源
     * @param params POST参数
     * @return 调用结果
     * @throws RestResponseParseException
     */
    public JSONObject request2(String service, String action, PostParameters params) throws RestResponseParseException {
        URL url;
        HttpURLConnection urlConn = null;
        String resultString = null;
        try {
            url = new URL(this.serviceSite + service + "/" + action);
            urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setRequestMethod("POST");
            urlConn.setConnectTimeout(httpTimeOut);
            urlConn.setReadTimeout(httpTimeOut);
            urlConn.setDoOutput(true);

            urlConn.setRequestProperty("connection", "keep-alive");
            urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + params.boundaryString());

            MultipartEntity reqEntity = params.getMultiPart();

            reqEntity.writeTo(urlConn.getOutputStream());

            if (urlConn.getResponseCode() == 200) {
                resultString = readString(urlConn.getInputStream());
                urlConn.getInputStream().close();
            } else {
                resultString = readString(urlConn.getErrorStream());
                urlConn.getErrorStream().close();
            }
            return new JSONObject(resultString);
        } catch (Exception e) {
            if (resultString != null && !resultString.isEmpty()) {
                throw new RestResponseParseException("error :" + resultString);
            } else {
                throw new RestResponseParseException("error :" + e.toString());
            }
        } finally {
            if (urlConn != null)
                urlConn.disconnect();
        }
    }

    // 读取访问服务的返回值
    private static String readString(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        String str = null;
        byte[] buffer = new byte[1024];
        int len = 0;
        try {
            while ((len = is.read(buffer)) > 0) {
                baos.write(buffer, 0, len);
            }
            byte[] data = baos.toByteArray();
            str = new String(data, "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return str;
    }

    public String getServiceSite() {
        return serviceSite;
    }

    public void setServiceSite(String serviceSite) {
        this.serviceSite = serviceSite;
    }

    public String getAppId() {
        return appId;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public String getAppKey() {
        return appKey;
    }

    public void setAppKey(String appKey) {
        this.appKey = appKey;
    }
    
    public void setHttpTimeOut(int httpTimeOut) {
        if (httpTimeOut < 0) {
            this.httpTimeOut = TIMEOUT;
        } else {
            this.httpTimeOut = httpTimeOut;
        }
    }
    
    public int getHttpTimeOut() {
        return this.httpTimeOut;
    }
	
}
